// components/SceneTest.tsx
import React, { useEffect, useState } from 'react';
import { View, Text, Button, ScrollView, StyleSheet, ActivityIndicator, Alert } from 'react-native';
import {
  getScenes,
  createScene,
  getSceneDetails,
  updateScene,
  deleteScene,
  addSceneDevice,
  removeSceneDevice,
  adjustScenePriority,
  activateScene,
  getActiveScenes,
  Scene // 导入 Scene 接口用于类型提示
} from '../../api/scene'; // 确保路径正确

const SceneTest = () => {
  const [testSceneId, setTestSceneId] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [statusMessage, setStatusMessage] = useState('');

  const runTest = async (testName: string, apiCall: () => Promise<any>) => {
    setStatusMessage(`Running ${testName}...`);
    setLoading(true);
    try {
      const response = await apiCall();
      console.log(`${testName} response:`, response.data);
      setStatusMessage(`${testName} succeeded!`);
      return response.data; // 返回数据以便后续使用
    } catch (error: any) {
      console.error(`${testName} error:`, error.response?.data || error.message || error);
      setStatusMessage(`${testName} failed: ${error.response?.data?.error?.message || error.message || '未知错误'}`);
      Alert.alert('API 测试失败', `${testName} 失败：${error.response?.data?.error?.message || error.message || '未知错误'}`);
      throw error; // 抛出错误以停止后续测试链
    } finally {
      setLoading(false);
    }
  };

  /**
   * Runs a comprehensive suite of tests for all scene-related API endpoints.
   *
   * The test sequence includes:
   * 1. Creating a new scene (with a unique name).
   * 2. Fetching the details of the created scene.
   * 3. Updating the scene's properties.
   * 4. Adding a device to the scene (requires a valid device ID).
   * 5. Adjusting the scene's priority (e.g., moving up).
   * 6. Manually activating the scene.
   * 7. Fetching the currently active scenes.
   * 8. Removing the device from the scene.
   * 9. Deleting the scene (cleanup).
   *
   * Each step uses the `runTest` helper to execute and report the result.
   * If any step fails, the process stops and an error message is set.
   *
   * @async
   * @returns {Promise<void>} Resolves when all tests complete or stops on failure.
   */
  const testAllSceneApis = async () => {
    setStatusMessage('Starting all scene API tests...');
    try {
      // 2. 测试创建场景
      const createResponse = await runTest('Create Scene', () =>
        createScene({
          name: `Test Scene ${Date.now()}`, // 使用时间戳确保名称唯一
          description: 'This is a test scene created by API test',
          enabled: true,
        })
      );
      // 从创建响应中获取场景ID，用于后续测试
      if (createResponse && createResponse.data && createResponse.data.id) {
        setTestSceneId(createResponse.data.id);
        const newSceneId = createResponse.data.id;

        // 3. 测试获取场景详情
        await runTest('Get Scene Details', () => getSceneDetails(newSceneId));

        // 4. 测试更新场景
        await runTest('Update Scene', () =>
          updateScene(newSceneId, {
            name: `Updated Test Scene ${Date.now()}`,
            enabled: false,
          })
        );

        // 5. 测试添加/更新场景设备
        // 注意：这里的 device_id 需要是后端实际存在的设备ID
        // 并且 params 应该与该设备类型预定义的参数匹配 
        const dummyDeviceId = 101; // 假设有一个设备ID为101
        await runTest('Add Device to Scene', () =>
          addSceneDevice(newSceneId, dummyDeviceId)
        );

        // 6. 测试调整场景优先级
        await runTest('Adjust Scene Priority - move_up', () =>
          adjustScenePriority(newSceneId, { action: 'move_up' })
        );
        // 也可以测试 set_priority
        // await runTest('Adjust Scene Priority - set_priority', () =>
        //   adjustScenePriority(newSceneId, { action: 'set_priority', priority: 5 })
        // );


        // 7. 测试手动激活场景
        await runTest('Activate Scene', () => activateScene(newSceneId));

        // 8. 测试获取当前生效场景
        await runTest('Get Active Scenes', getActiveScenes);

        // 9. 测试移除场景设备
        await runTest('Remove Scene Device', () =>
          removeSceneDevice(newSceneId, dummyDeviceId)
        );

        // 10. 测试删除场景 (通常放在最后)
        await runTest('Delete Scene', () => deleteScene(newSceneId));
        setTestSceneId(null); // 删除后清空ID
      } else {
        setStatusMessage('Create Scene failed to return a valid ID, stopping tests.');
      }
    } catch (overallError) {
      console.error('One or more scene API tests failed.', overallError);
      setStatusMessage('One or more tests failed. Check console for details.');
    }
  };

  useEffect(() => {
    // 可以在组件挂载时自动运行所有测试，或者只提供按钮让用户手动点击
    // testAllSceneApis();
  }, []);

  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>场景 API 测试</Text>
      <Text style={styles.status}>{statusMessage}</Text>
      {loading && <ActivityIndicator size="large" color="#0000ff" />}

      <View style={styles.buttonContainer}>
        <Button title="运行所有场景API测试" onPress={testAllSceneApis} disabled={loading} />
      </View>

      <View style={styles.buttonContainer}>
        <Button title="获取所有场景" onPress={() => runTest('Get All Scenes', getScenes)} disabled={loading} />
      </View>
      <View style={styles.buttonContainer}>
        <Button title="创建场景" onPress={() => runTest('Create Scene', () => createScene({ name: `Manual Test Scene ${Date.now()}`, description: 'Manual creation', enabled: true }))} disabled={loading} />
      </View>
      {/* 这里的按钮为了手动测试，需要手动输入ID，或者先通过创建场景获取ID */}
      {testSceneId && (
        <>
          <Text style={styles.currentIdText}>当前测试场景ID: {testSceneId}</Text>
          <View style={styles.buttonContainer}>
            <Button title="获取场景详情" onPress={() => runTest('Get Scene Details', () => getSceneDetails(testSceneId))} disabled={loading} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="更新场景" onPress={() => runTest('Update Scene', () => updateScene(testSceneId, { name: `Manual Updated ${Date.now()}`, enabled: false }))} disabled={loading} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="添加/更新场景设备" onPress={() => runTest('Add Scene Device', () => addSceneDevice(testSceneId, 101))} disabled={loading} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="调整场景优先级 (上移)" onPress={() => runTest('Adjust Scene Priority', () => adjustScenePriority(testSceneId, { action: 'move_up' }))} disabled={loading} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="手动激活场景" onPress={() => runTest('Activate Scene', () => activateScene(testSceneId))} disabled={loading} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="移除场景设备" onPress={() => runTest('Remove Scene Device', () => removeSceneDevice(testSceneId, 101))} disabled={loading} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="删除场景" onPress={async () => {
              await runTest('Delete Scene', () => deleteScene(testSceneId));
              setTestSceneId(null);
            }} disabled={loading} />
          </View>
        </>
      )}
      <View style={styles.buttonContainer}>
        <Button title="获取当前生效场景" onPress={() => runTest('Get Active Scenes', getActiveScenes)} disabled={loading} />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
    color: '#333',
  },
  status: {
    fontSize: 16,
    marginBottom: 10,
    textAlign: 'center',
    color: '#666',
  },
  currentIdText: {
    fontSize: 14,
    fontWeight: 'bold',
    marginVertical: 10,
    textAlign: 'center',
    color: '#007bff',
  },
  buttonContainer: {
    marginBottom: 10,
  },
});

export default SceneTest;